<script setup>
import { ref } from 'vue';
import { random } from '@/utils/index.js';
import { showToast } from 'vant';
import {checkMobile} from '@/utils/validate.js';
import {getSmsApi} from '@/api/user';
import useUserStore from '@/stores/user';
import { useRouter } from 'vue-router';

const router = useRouter()

const user =useUserStore()

const formData=ref({
    mobile:'17364306786',
    code:'3856',
})


const onSubmit = async (values) => {  
   const { msg, state, data } = await user.login(values)
   if(state===200){
    router.push('/nowPlaying')
    user.userinfo=data
    console.log(user.userinfo);
    
   }else{
    showToast(msg)
   }
};

// 随机logo
const logoName = ref(random(1, 2));

setInterval(() => {
    logoName.value = random(1, 2);
}, random(1, 2) * 1000);

//发送验证码
//1 验证手机号是否合法
// 2.文字变化　变成倒计时
// 3.禁用按钮
// 4.setInterval实现倒计时
// 5.到了临界值 文字变回来‧时间重置 关闭定时器
const sms = ref({
    msg: '发送验证码',
    time: 10,
    disabled: false,
    to: null,
})

const onPostSms =async () => {

    if (checkMobile(formData.value.mobile))return showToast('不合法');

    const res =await getSmsApi({mobile:formData.value.mobile,type:'login'})

    console.log({mobile:formData.value.mobile,type:'login'});    

    console.log(res);
    if(res.state===400)return showToast(res.msg)    
    
    sms.value.disabled=true
    sms.value.to=setInterval(()=>{
        sms.value.time--
        sms.value.msg=`${sms.value.time}`
        if( sms.value.time<=0){
            sms.value.disabled=false
            sms.value.msg='发送验证码'            
            sms.value.time=10
            clearInterval(sms.value.to)
        }

    },1000)


}


</script>

<template>

    <div class="login-container">
        <img :src="`/src/assets/img/login${logoName}.jpg`">
    </div>

    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field v-model="formData.mobile" name="mobile" placeholder="手机号" :rules="[{ required: true, message: '请填写手机号' }]">

                <!-- 发送验证码 -->
                <template #button>
                    <van-button size="small" @click="onPostSms" :disabled="sms.disabled">{{ sms.msg }}</van-button>
                </template>

            </van-field>

            <van-field v-model="formData.code" type="code" name="code" placeholder="验证码"
                :rules="[{ required: true, message: '请填写验证码' }]" />


        </van-cell-group>
        <div style="margin: 30px;">
            <van-button round block type="primary" native-type="submit" >
                提交
            </van-button>
        </div>
    </van-form>


</template>

<style scoped lang="less">
.login-container {
    width: 100%;
    height: 200px;
    box-sizing: border-box;

    img {
        width: 100%;
    }


}

.van-field {
    height: 70px;
    line-height: 35px;
    width: 80%;
    margin-left: 15px;

    .van-button {
        font-size: 12px;
        border: 0;
        color: @inacColor;
    }
}
</style>